package com.summit.exam.servlet;

import com.summit.exam.dbdao.PaperDao;
import com.summit.exam.dbdao.QuestionDao;
import com.summit.exam.entity.QuestionBean;
import com.summit.exam.utils.UploadExcel;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class fileUpLoadServlet extends HttpServlet {
    public fileUpLoadServlet() {
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();

        String upLoadDir = this.getServletContext().getRealPath("/WEB-INF/upload");
        new File(upLoadDir);

        FileItemFactory factory = new DiskFileItemFactory();
        //文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置所有上传数据的最大值，单位字节long  1M
        upload.setSizeMax(1024*1024);
        //设置单个文件上传的最大值
        upload.setFileSizeMax(1024*1024);
        //设置编码格式
        upload.setHeaderEncoding("UTF-8");

        List fileItem = null;

        try {
            fileItem = upload.parseRequest(req);
        } catch (Exception  var21) {
            var21.printStackTrace();
        }

        Iterator it = fileItem.iterator();

        String path = null;
        while(it.hasNext()) {
            FileItem fitem = (FileItem)it.next();
            if (!fitem.isFormField()) {
                String pathSrc = fitem.getName();
                if (!pathSrc.trim().equals("")) {
                    int start = pathSrc.lastIndexOf(92);
                    String fileName = pathSrc.substring(start + 1);
                    path = fileName;
                    File pathDest = new File(upLoadDir, fileName);
                    if(!pathDest.exists()){
                        //先得到文件的上级目录，并创建上级目录，在创建文件
                        pathDest.getParentFile().mkdir();
                        try {
                            //创建文件
                            pathDest.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    try {
                        fitem.write(pathDest);
                    } catch (Exception var19) {
                        var19.printStackTrace();
                    } finally {
                        fitem.delete();
                    }
                }
            }
        }

        //文件处理
        ArrayList<QuestionBean> questionArrayList = UploadExcel.excel(upLoadDir + "\\" + path);

        PaperDao paperService = new PaperDao();
        int paperId = paperService.getMaxpaperId();

        path = path.substring(0, path.indexOf('.'));

        //插入试题名称
        paperService.addPaper(paperId + 1, path);

        //更改答案存储方式
        QuestionDao questionService = new QuestionDao();

        /*for (int i = 0; i < questionArrayList.size(); i++) {
            QuestionBean question = questionArrayList.get(i);

            System.out.println("-----" + question.getAnswer());

            questionArrayList.get(i).setAnswer(getString(question.getAnswer()));


        }*/

        questionService.insertmoreQuestion(questionArrayList, paperId + 1);


        req.setAttribute("str", "true");
        req.getRequestDispatcher("/ExamSystem/techweb/selectPaper.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }

    public String getString(String str) {
        String result = "";

        if (str == null){
            return "5";
        }

        for (int i = 0; i < str.length(); i++) {
            result += (str.charAt(i) - 64) + ((i + 1) == str.length() ? "" : ":");
        }

        return result;
    }
}

